<template>
  <a-locale-provider :locale="locale">
    <div id="app">
      <router-view />
      <div
        v-if="message"
        class="notification el-notification right"
        style="bottom: 16px;z-index: 2000;"
      >
        <i class="el-notification__icon el-icon-info"></i>
        <div class="el-notification__group is-with-icon">
          <h2 class="el-notification__title">系统通知</h2>
          <div class="el-notification__content">
            <p>{{ message }}</p>
          </div>
          <div class="el-notification__closeBtn el-icon-close" @click="handleClose"></div>
        </div>
      </div>
      <el-dialog
        class="notice-dialog"
        v-if="messageData.length > 0"
        :close-on-click-modal="false"
        title="系统公告"
        width="800px"
        :visible.sync="visible"
        @close="handleDialogClose"
      >
        <el-form label-width="100px">
          <el-form-item label="标题：">{{ messageData[readNum].title && messageData[readNum].title }}</el-form-item>
          <!-- <el-form-item
            label="描述："
          >{{ messageData[readNum].description && messageData[readNum].description }}</el-form-item>-->
          <el-form-item
            label="内容："
          >{{ messageData[readNum].content && messageData[readNum].content }}</el-form-item>
          <el-form-item label="附件：">
            <template
              v-if="messageData[readNum].notifyAttachmentList && messageData[readNum].notifyAttachmentList.length"
            >
              <li v-for="(item,index) in messageData[readNum].notifyAttachmentList" :key="index">
                <a :href="item.savePath" target="_blank">{{ '附件' + Number(index + 1) }}</a>
              </li>
            </template>
            <template v-else>无</template>
          </el-form-item>
          <el-form-item label="不再提示：">
            <el-checkbox v-model="messageData[readNum].check" @change="handleRefuseNotice" />
          </el-form-item>
        </el-form>
        <div slot="footer" v-if="messageData.length > 1">
          <el-button v-show="readNum > 0" class="fl" @click="handleReadPre">上一条</el-button>
          <el-button
            type="primary"
            v-show="messageData.length > 1 && readNum < messageData.length-1"
            @click="handleReadNext"
          >下一条</el-button>
        </div>
      </el-dialog>
    </div>
  </a-locale-provider>
</template>

<script>
import zhCN from 'ant-design-vue/lib/locale-provider/zh_CN'
import { AppDeviceEnquire } from '@/utils/mixin'
import { getDicTree } from '@/api/dictionary'
import { setSession, getSession } from '@/utils/util'
import { STORE } from '@/store/mutation-types'
import { getPublicRead, updateRead, publicRead } from '@/api/notify'
import { asyncRouterMap } from '@/config/router.config.js'
import { mapActions } from 'vuex'

export default {
  mixins: [AppDeviceEnquire],
  data() {
    return {
      locale: zhCN,
      userInfo: this.$store.getters.userInfo,
      message: null,
      visible: false,
      messageData: [],
      readNum: 0
    }
  },
  components: {},
  mounted() {
    // 将下面的代码放到BasicLayout去了
    // if (!this.$ls.get('dictionaryData')) {
    //   getDicTree('', {}).then(res => {
    //     console.log('app tree res', res)
    //     if (res.state === '000000' && res.data.length > 0) {
    //       this.$ls.set('dictionaryData', res.data)
    //     }
    //   })
    // }
  },
  computed: {},
  watch: {
    $route: {
      handler(n, o) {
        if (this.$ls.get('userInfo') && !getSession('haveSeeNotice')) {
          return
          // 登录进来时只看一次，后面不再弹出
          getPublicRead().then(res => {
            this.messageData = res.data
            if (this.messageData.length > 0) {
              this.messageData.map(v => {
                v.check = false
              })
              this.visible = true
            }
          })
        }
      },
      deep: true
    }
  },
  created() {
    //在页面加载时读取sessionStorage里的状态信息
    // if (this.$ls.get('Store-State')) {
    //   this.$store.replaceState(Object.assign({}, this.$store.state, this.$ls.get('Store-State')))
    //   this.userInfo = this.$store.getters.userInfo
    // }

    // window.addEventListener('beforeunload', () => {
    //   this.$ls.set('Store-State', this.$store.state)
    // })
    this.userInfo = this.$store.getters.userInfo
    if (this.userInfo && this.userInfo.userId) {
      // 有用户信息时，建立链接
      this.initWebSocket()
    } else {
      return this.Logout(true)
    }
  },
  methods: {
    ...mapActions(['Logout']),
    handleRefuseNotice(e) {
      // console.log('e', e)
      if (e) {
        this.$nextTick(() => {
          this.messageData[this.readNum].check = true
          this.messageData.splice()
        })
      } else {
        this.$nextTick(() => {
          this.messageData[this.readNum].check = false
          this.messageData.splice()
        })
      }
    },
    // dialog 关闭调用
    async handleDialogClose() {
      console.log('close')
      let arr = []
      this.messageData.map(v => {
        if (v.check) {
          arr.push(v)
        }
      })
      console.log('arr', arr)
      if (arr.length > 0) {
        arr.map(v => {
          v.readMode = 1
        })
        const res = await publicRead(arr)
        if (res.state === '000000') {
          console.log('已读')
        }
      }
      setSession('haveSeeNotice', true)
    },
    handleReadNext() {
      this.readNum += 1
      // console.log('check', this.messageData[this.readNum].check)
    },
    handleReadPre() {
      this.readNum -= 1
    },
    // 系统通知点击关闭
    handleClose() {
      this.message = null
    },
    initWebSocket() {
      if (this.userInfo && this.userInfo.userId) {
        //初始化weosocket
        const wsuri = 'ws://192.168.14.2:8888/wxserver/' + this.userInfo.userId
        this.websock = new WebSocket(wsuri)
        this.websock.onmessage = this.websocketonmessage
        this.websock.onopen = this.websocketonopen
        this.websock.onerror = this.websocketonerror
        this.websock.onclose = this.websocketclose
      }
    },
    websocketonopen() {
      console.log('链接成功')
      //连接建立之后执行send方法发送数据
      let actions = { test: '12345' }
      this.websocketsend(JSON.stringify(actions))
    },
    websocketonerror() {
      //连接建立失败重连
      this.initWebSocket()
    },
    websocketonmessage(e) {
      //数据接收
      console.log('接收 e', e)
      if (e.data !== '连接成功') {
        this.message = e.data
        this.$notify({
          title: '系统通知',
          type: 'info',
          message: `${e.data}`,
          position: 'bottom-right',
          duration: 0
        })
      }
      // const redata = JSON.parse(e.data)
    },
    websocketsend(Data) {
      //数据发送
      this.websock.send(Data)
    },
    websocketclose(e) {
      //关闭
      console.log('断开连接', e)
    }
  }
}
</script>
<style>
#app {
  height: 100%;
}
</style>

<style scoped>
#app >>> .el-notification__group {
  width: 100%;
}

.notice-dialog >>> .el-dialog__footer {
  overflow: hidden;
}
</style>
